/**
 * cn.ucox.web.application.interceptor.SessionInterceptor
 *
 * @author chenw
 * @create 16/2/3.15:35
 * @email javacspring@hotmail.com
 */

package cn.com.oceansoft.application.interceptor;

import cn.com.oceansoft.application.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 会话拦截器
 *
 * @author chenw
 * @create 16/2/3 15:35
 * @email javacspring@gmail.com
 */
public class SessionInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private String loginUrl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long _start = System.currentTimeMillis();
        String requestUrl = request.getRequestURI().toLowerCase();
        boolean isAjax = request != null && "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
        boolean isLogin = (request.getSession().getAttribute(Constant.CURRENT_MEMBER) != null);
        request.setAttribute("START_REQUEST", _start);
        System.out.print(String.format("RequestStart:=====>%d Access URL=>%s", _start, requestUrl));
        if (!isLogin) {//非登录用户
            if (isAjax) {
                PrintWriter out = response.getWriter();
                out.println(new String("{\"code\":\"10400\", \"msg\":\"请登录!\"}".getBytes("UTF-8"), "ISO8859-1"));
                out.flush();
                out.close();
            } else {
                response.sendRedirect(request.getContextPath()+loginUrl+"?return_url="+requestUrl);
            }
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long _end = System.currentTimeMillis();
        System.out.print(String.format("\nRequestEnd:=====>%d，共计耗时:%s毫秒\n\n", _end, (_end - Long.valueOf(request.getAttribute("START_REQUEST").toString()))));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) throws Exception {
    }

    public String getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }
}

